<template>
  <div class="flex-1">
    <div class="flex justify-between mb-4 items-center">
      <div>新增素材</div>
      <a-button type="ghost" class="text-blue-500 border border-blue-500" @click="create">
        <PlusOutlined />
      </a-button>
    </div>
    <a-card :body-style="{ padding: '1rem' }">
      <a-table :columns="materialColumns" :data-source="form.materials">
        <template #bodyCell="{ record, column }">
          <template v-if="column.dataIndex === 'operation'">
            <a-button type="link" danger @click="del(record.id)">
              <DeleteOutlined />
            </a-button>
          </template>
          <template v-else-if="column.dataIndex === 'url'">
            <div class="flex justify-center gap-4 items-center">
              <XImage :src="record.url" :height="80"></XImage>
              <div class="add-material" @click="selectFile(record as any)">
                <PlusOutlined />
              </div>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'second'">
            <a-input-number v-model:value="record.second"></a-input-number>
          </template>
          <template v-else-if="column.dataIndex === 'name'">
            <a-input class="w-fit" allow-clear v-model:value="record.name"></a-input>
          </template>
        </template>
      </a-table>
    </a-card>

    <FileSelector @select="onSelect" v-model:visible="visible" :type="LIBRARY_ENUM.IMAGE" />
  </div>
</template>

<script setup lang="ts">
import { nanoid } from 'nanoid';
import { form } from '../../data/form';
import { materialColumns } from '../../data/columns';
import { LIBRARY_ENUM } from '@/enum/system';
import type { Material } from '@/api/modules/lcd/publicize';

const currentFile = ref<Material>();
const visible = ref(false);
const create = () => {
  form.value.materials.push({
    name: '',
    second: 0,
    url: '',
    id: nanoid(),
  });
};

const selectFile = (item: Material) => {
  currentFile.value = item;
  visible.value = true;
};

const onSelect = (item: string) => {
  form.value.materials.forEach(e => {
    if (currentFile.value && currentFile.value.id === e.id) {
      console.log(e);
      e.url = item;
    }
  });
};

const del = (id: string) => {
  form.value.materials = form.value.materials.filter(e => e.id !== id);
};
</script>

<style lang="scss" scoped>
table {
  table-layout: fixed;
  width: 100%;
  text-align: center;
}
div.add-material {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed var(--border-color);
  cursor: pointer;
}
</style>
